package zz.listener;

//import javax.servlet.ServletContext;
//import javax.servlet.ServletContextEvent;
//
//public class OnLineListener {
//    ServletContext application = null;
//    public OnLineListener(){
//
//    }
//    public void contextInitialized(ServletContextEvent sce){
//        System.out.println("------------服务器启动了---------------");
//
//    }
//}


//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpSessionEvent;
//import javax.servlet.http.HttpSessionListener;
//
//public class OnLineListener implements HttpSessionListener {
//    @Override
//    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
//        ServletContext application=httpSessionEvent.getSession().getServletContext();
//        Integer Online_number=(Integer)application.getAttribute("Online_number");
//        if(null==Online_number)
//            Online_number=0;
//
//        Online_number++;
//        application.setAttribute("Online_number",Online_number);
//
//        System.out.println("新增一位在线用户！");
//
//    }
//
//    @Override
//    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
//        ServletContext application =httpSessionEvent.getSession().getServletContext();
//        Integer Online_number=(Integer)application.getAttribute("Online_number");//要转换为数字时 要默认用（Integer）强转
//        if(null==Online_number)
//        {
//            Online_number=0;
//        }
//        else
//            Online_number--;
//        application.setAttribute("Online_number",Online_number);
//        System.out.println("一位用户离线");
//    }
//}


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnLineListener implements HttpSessionListener, ServletContextListener {
    private int count1 = 0; // 用于统计在线人数
    @Override
    public void sessionCreated(HttpSessionEvent hse) {
//        count1++; // Session对象创建时count变量加1
//        ServletContext context = hse.getSession().getServletContext();
//        context.setAttribute("count", new Integer(count));
        hse.getSession().setAttribute("count1",count1);
        count1++;
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
//        count1--; // session对象销毁时count变量减1
//        ServletContext context = hse.getSession().getServletContext();
//        context.setAttribute("count", new Integer(count));
        hse.getSession().setAttribute("count1",count1);
        count1--;
    }

    private int count2 = 0;//登陆人数
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().setAttribute("count2", count2);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().removeAttribute("count2");
    }
}

